#!/bin/bash

#--------------------------------------------
# 功能：IOS打包
# 使用说明：运行脚本，配置相对应的config.ini文件，打出ipa
# 作者：张国东
# E-mail:651247149@qq.com
# 创建日期：2014/01/23
#--------------------------------------------
#--------------------------------------------
# 修改日期：2014/01/23
# 修改人：张国东
# 修改内容：在打包app的时候出错时，不再执行下一步操作,提高灵活性 
#		  支持workspace和project,自动搜索打包出来的母包app
#--------------------------------------------

#  定义变量的时候前面后面别加空格
cd $(dirname "$0")/    #去到当前工作目录

if [ ! -f "$(dirname "$0")/config.ini" ]; then
	echo '文件不存在'
	exit;
fi

GetKey(){    
    section=$(echo $1 | cut -d '.' -f 1)    
    key=$(echo $1 | cut -d '.' -f 2)    
    sed -n "/\[$section\]/,/\[.*\]/{    
     /^\[.*\]/d    
     /^[ \t]*$/d    
     /^$/d    
     /^#.*$/d    
     s/^[ \t]*$key[ \t]*=[ \t]*\(.*\)[ \t]*/\1/p    
    }" config.ini    
}


#=======================初始化文件数据======================================
identifier=$(GetKey "app.identifier"); #项目identifier
if [ -z "$identifier" ]; then
	echo "identifier为空 打包停止！"
	exit;
fi
version=$(GetKey "app.version");  #应用版本
build=$(GetKey "app.build"); #应用构建号
supportIpad=$(GetKey "app.supportIpad"); #是否支持ipad
projectName=$(GetKey "app.projectName"); #项目名称
appkey=$(GetKey "app.appkey"); #项目的appKay
schemeName=$(GetKey "app.schemeName"); 
targerName=$(GetKey "app.targerName"); 
mobileprovisionPath=$(GetKey "app.mobileprovisionPath"); #用户证书
P12PathFile=$(GetKey "app.P12PathFile"); #用户信息P12文件
password=$(GetKey "app.password"); #用户信息P12 密码
workspaceName=$(GetKey "app.workspaceName");
ipaFilePath=$(GetKey "app.ipaFilePath");

dataPath="path"

#增加默认设置
if [ -z "$version" ];then
	version='1.0.1'
fi
if [ -z "$build" ];then
	build='1'
fi
#=======================初始化文件==========================================

#=======================文件夹准备==========================================
distDir="$(dirname "$0")/OutIPAs"   #定义输出目录
echo $distDir
releaseDir="build/Debug-iphoneos"               #编译目录   发布版本应该换成distribut的目录
rm -rdf  "$releaseDir"
rm -rdf "$distDir"                         #移除旧的输出目录
mkdir -p "$distDir"  #创建ipa 输出目录
#=======================文件夹准备==========================================

#=======================证书准备============================================
if [ -f "$(dirname "$0")/$P12PathFile" ]; then 
	#创建钥匙链
	security create-keychain -p $identifier "$identifier.keychain"
	#解锁，否则回弹框等待输入密码
	security unlock-keychain -p $identifier "$identifier.keychain"  
	#导入证书到keychain中
	security import $P12PathFile -k "$identifier.keychain" -P "$password" -T /usr/bin/codesign
fi


#安装证书 获取 uuid 
if [ -f "$(dirname "$0")/${mobileprovisionPath}" ]; then
	uuid=`grep UUID -A1 -a ${mobileprovisionPath} | grep -o "[-A-Z0-9]\{36\}"`
	cp $mobileprovisionPath ~/Library/MobileDevice/Provisioning\ Profiles/$uuid.mobileprovision
fi

if [ ! -n "$uuid" ]; then
	echo "证书为空,打包停止！"
	exit;
fi

#=======================准备编译============================================
cd ios
project_path=$(pwd)
workspace_name='*.xcworkspace'
ls $project_path/$workspace_name &>/dev/null
rtnValue=$?
if [ $rtnValue = 0 ];then
	workspaceName=$(echo $(basename $project_path/$workspace_name))
	echo "build_workspace =$build_workspace"
	isWorkspace=true; 
else
	isWorkspace=false;
fi

#修改 项目的identifier 
/usr/libexec/PlistBuddy -c "Set:CFBundleIdentifier $identifier" $workspaceName/$workspaceName-Info.plist #修改identifier
#修改 项目的版本号
/usr/libexec/PlistBuddy -c "Set:CFBundleShortVersionString $version" $workspaceName/$workspaceName-Info.plist #修改version
#修改 项目的构建号
/usr/libexec/PlistBuddy -c "Set:CFBundleVersion $build" $workspaceName/$workspaceName-Info.plist #修改build

if [ ! -z "$projectName" ];then
	/usr/libexec/PlistBuddy -c "Set:CFBundleName $projectName" $workspaceName/$workspaceName-Info.plist #修改build
	/usr/libexec/PlistBuddy -c "Set:CFBundleDisplayName $projectName" $workspaceName/$workspaceName-Info.plist #修改build
fi

#清除项目之前编译的文件
xcodebuild clean

#编译workspace
if $isWorkspace; then
	xcodebuild -workspace $workspaceName -scheme $schemeName -configuration Release -derivedDataPath  "$dataPath"   PROVISIONING_PROFILE=$uuid
	dataPath+='/Build/Products/Release-iphoneos/'
else
	xcodebuild -target $targerName  -derivedDataPath  "$dataPath" PROVISIONING_PROFILE=$uuid
	dataPath+='/Release-iphoneos/'
fi
#编译project

#判断编译结果
if test $? -eq 0
 then
	echo "~~~~~~~~~~~~~~~~~~~编译成功~~~~~~~~~~~~~~~~~~~"
else
	echo "~~~~~~~~~~~~~~~~~~~编译失败~~~~~~~~~~~~~~~~~~~" 
	echo "\n" 
	security delete-keychain "$identifier.keychain" #编译失败，删除钥匙链
	exit 1
fi

#=======================编译完成============================================
#获取打包出来的app 

project_path=$(pwd)
app_name='*.app'
ls $project_path/$dataPath/$app_name &>/dev/null
rtnValue=$?
echo "rtnValue ==== $rtnValue"
if [ $rtnValue = 0 ]; then
	appName=$(echo $(basename $project_path/$dataPath$app_name))
	echo "appName =======  $appName"
	#将打出来的母包 app  打出 ipa
	if $isWorkspace; then
  	 xcrun -sdk iphoneos PackageApplication -v "$dataPath$appName" -o "$ipaFilePath" PROVISIONING_PROFILE=$uuid
	else
  	 xcrun -sdk iphoneos PackageApplication -v "$dataPath$appName" -o "$ipaFilePath" PROVISIONING_PROFILE=$uuid
	fi
else
	echo "获取app 失败  "
	
fi
#删除钥匙链
	security delete-keychain "$identifier.keychain"
exit 1 


#=======================打包完成============================================

